//
//  TravelVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/10/28.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "TravelVC.h"
#import "XRCollectionViewCell.h"
#import "XRWaterfallLayout.h"

#import "TravelsDetailVC.h"
#import "TravelsSearchVC.h"

@interface TravelVC ()<UICollectionViewDataSource, XRWaterfallLayoutDelegate,UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation TravelVC
{
    UITextField *_searchBarTraTf;
    NSString *_titleStr;
    CGSize _titleStrSize;
    NSString *_contentStr;
    CGSize _contentStrSize;
    
    //请求下来的字典
    NSDictionary *_responseDic;
    //请求下来的数组
    NSMutableArray *_responseArr;
    NSInteger _currentPage;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSearchTraBar];
    _responseArr = [NSMutableArray array];
    _currentPage = 1;
    [self requestForTravels:_currentPage isFirst:YES];
    //创建瀑布流布局
    XRWaterfallLayout *waterfall = [XRWaterfallLayout waterFallLayoutWithColumnCount:2];
    
    //或者一次性设置
    [waterfall setColumnSpacing:20 rowSpacing:10 sectionInset:UIEdgeInsetsMake(10, 10, 10, 10)];
    
    //设置代理，实现代理方法
    waterfall.delegate = self;
    
    //创建collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:waterfall];
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"XRCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    [self refreshDown];
    [self refreshLoadMore];
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
}
//导航栏添加搜索框
- (void)addSearchTraBar{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0,  0, KScreenWidth, 33)];
    UIImageView *logoImageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, -10, 50, 50)];
    logoImageV.image = [UIImage imageNamed:@"logo_transparent"];
    [bgView addSubview:logoImageV];
    _searchBarTraTf = [[UITextField alloc]initWithFrame:CGRectMake(60, 0, KScreenWidth-80, 33)];
    _searchBarTraTf.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    _searchBarTraTf.leftViewMode = UITextFieldViewModeAlways;
    _searchBarTraTf.placeholder = @"搜索游记";
    _searchBarTraTf.tintColor = [UIColor blackColor];
    _searchBarTraTf.font = [UIFont systemFontOfSize:14];
    _searchBarTraTf.backgroundColor = blackLineColore;
    _searchBarTraTf.layer.borderWidth = 1;
    _searchBarTraTf.layer.borderColor = [UIColor grayColor].CGColor;
    _searchBarTraTf.layer.cornerRadius = 8;
    
    UIButton *searchBtn =[[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth-120, 3, 35, 30)];
    _searchBarTraTf.rightView = searchBtn;
    _searchBarTraTf.rightViewMode = UITextFieldViewModeAlways;
    searchBtn.backgroundColor = White_Color;
    searchBtn.layer.cornerRadius = 5;
    [searchBtn setImage:[UIImage imageNamed:@"组-3"] forState:UIControlStateNormal];
    searchBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [searchBtn addTarget:self action:@selector(searchTraAction) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:_searchBarTraTf];
    [_searchBarTraTf addSubview:searchBtn];
    
    self.navigationItem.titleView = bgView;
}
#pragma - mark RequestForTravels
- (void)requestForTravels:(NSInteger)currentPage isFirst:(BOOL)isFirst{
    //参数
    NSDictionary *parameters = @{
                                 @"pageNum": @(currentPage),
                                 @"pageSize":@"10",
                                 };
    [SVProgressHUD showWithStatus:@"请求中"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/travel/list.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        [_collectionView.mj_header endRefreshing];
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        NSArray *temp = _responseDic[@"list"];
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            if (isFirst) {
                if (temp.count == 0) {
                    [SVProgressHUD showImage:nil status:@"暂无数据"];
                }
                [_responseArr removeAllObjects];
            }
            [_responseArr addObjectsFromArray:temp];
            
            if (temp.count < 10) {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                [_collectionView.mj_footer endRefreshing];
            }
            //请求成功
            [_collectionView reloadData];
            [SVProgressHUD dismiss];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求游记列表失败"];
    }];
}
//下拉刷新
- (void)refreshDown{
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage = 1;
        [self requestForTravels:_currentPage isFirst:YES];
    }];
}
//上提加载更多
- (void)refreshLoadMore{
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage++;
        [self requestForTravels:_currentPage isFirst:NO];
    }];
}
//根据item的宽度与indexPath计算每一个item的高度
- (CGFloat)waterfallLayout:(XRWaterfallLayout *)waterfallLayout itemHeightForWidth:(CGFloat)itemWidth atIndexPath:(NSIndexPath *)indexPath {
    _titleStr = _responseArr[indexPath.row][@"title"];
    _titleStrSize = [BAAutoSizeWithWH BA_AutoSizeOfHeghtWithText:_titleStr font:[UIFont systemFontOfSize:16] width:(KScreenWidth/2 - 20)];
    _contentStr = _responseArr[indexPath.row][@"firstContent"];
    _contentStrSize = [BAAutoSizeWithWH BA_AutoSizeOfHeghtWithText:_contentStr font:[UIFont systemFontOfSize:12] width:(KScreenWidth/2 - 20)];
    return 100 +25 +_titleStrSize.height +_contentStrSize.height + 5;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _responseArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XRCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = superBackgroundColor.CGColor;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(1, 1, KScreenWidth/2 - 20 - 2, 100 - 2)];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    NSString *urlStr = _responseArr[indexPath.row][@"thumbs"];
    if (urlStr.length == 2) {
        imageView.image = [UIImage imageNamed:@"默认图片"];
    }else{
        urlStr = [urlStr substringFromIndex:1];
        urlStr = [urlStr substringToIndex:83];
        [imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"默认图片"]];
    }
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    [cell.contentView addSubview:imageView];
    NSString *titleNameStr = _responseArr[indexPath.row][@"title"];
    CGSize titleNameStrSize = [BAAutoSizeWithWH BA_AutoSizeOfHeghtWithText:titleNameStr font:[UIFont systemFontOfSize:16] width:(KScreenWidth/2 - 20)];
    UILabel *titleName = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, KScreenWidth/2 - 20, titleNameStrSize.height)];
    //    titleName.backgroundColor = Red_Color;
    titleName.text = titleNameStr;
    titleName.numberOfLines = 0;
    titleName.textColor = Theme_Color;
    titleName.font = [UIFont systemFontOfSize:16];
    [cell.contentView addSubview:titleName];
    
    UIImageView *iconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(1, 100 + titleNameStrSize.height, 20, 20)];
    iconImageView.layer.masksToBounds = YES;
    iconImageView.layer.cornerRadius = 10;
    NSString *iconStr = _responseArr[indexPath.row][@"userPhoto"];
    [iconImageView sd_setImageWithURL:[NSURL URLWithString:iconStr] placeholderImage:[UIImage imageNamed:@"userIcon"]];
    [cell.contentView addSubview:iconImageView];
    
    UILabel *authorLb = [[UILabel alloc]initWithFrame:CGRectMake(28, 100 + titleNameStrSize.height, KScreenWidth/2 - 40, 25)];
    authorLb.text = _responseArr[indexPath.row][@"author"];
//    authorLb.backgroundColor = Red_Color;
    authorLb.textColor = Theme_Color;
    authorLb.font = [UIFont systemFontOfSize:12];
    [cell.contentView addSubview:authorLb];
    
//    UIImageView *commentNumImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 20 - 41, 100 + 7 + titleNameStrSize.height, 13, 11.5)];
//    commentNumImageView.image = [UIImage imageNamed:@"comment_icon"];
//    [cell.contentView addSubview:commentNumImageView];
//    
//    UILabel *commentNumLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 20 - 28, 105+titleNameStrSize.height, 28, 15)];
//    commentNumLb.text = @"3333";
//    commentNumLb.textColor = Theme_Color;
//    commentNumLb.font = [UIFont systemFontOfSize:10];
//    [cell.contentView addSubview:commentNumLb];
    
    _contentStr = _responseArr[indexPath.row][@"firstContent"];
    _contentStrSize = [BAAutoSizeWithWH BA_AutoSizeOfHeghtWithText:_contentStr font:[UIFont systemFontOfSize:12] width:(KScreenWidth/2 - 20)];
    UILabel *contentLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 100+25+titleNameStrSize.height, KScreenWidth/2 - 20, _contentStrSize.height)];
    contentLb.text = _contentStr;
    contentLb.numberOfLines = 0;
    contentLb.textColor = [UIColor grayColor];
    contentLb.font = [UIFont systemFontOfSize:12];
    [cell.contentView addSubview:contentLb];
    
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    TravelsDetailVC *vc = [[TravelsDetailVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.htmlUrlStr = _responseArr[indexPath.row][@"htmlUrl"];
    vc.travelsId = _responseArr[indexPath.row][@"id"];
    vc.travelsName = _responseArr[indexPath.row][@"title"];
    vc.travelTime = _responseArr[indexPath.row][@"createTime"];
    vc.travelIcon = _responseArr[indexPath.row][@"userPhoto"];
    vc.travelAuthor = _responseArr[indexPath.row][@"author"];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)searchTraAction{
    [_searchBarTraTf endEditing:YES];
    TravelsSearchVC *vc = [[TravelsSearchVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.searchKey = _searchBarTraTf.text;
    _searchBarTraTf.text = nil;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
